#include"Buffer.h"
#include<errno.h>
#include<sys/uio.h>
#include<unistd.h>
 //从fd上读取数据
 ssize_t Buffer::readFd(int fd,int* saveError)
 {
    char extrabuf[65536]={0};//栈上临时缓冲区 extrabuf
    struct iovec vec[2];
    const size_t writable=writableBytes();
    vec[0].iov_base=begin()+writerIndex_;
    vec[0].iov_len=writable;

    vec[1].iov_base=extrabuf;
    vec[1].iov_len=sizeof extrabuf;

    const int iovcnt=(writable < sizeof extrabuf)? 2:1;//避免不必要的性能开销
    const ssize_t n= ::readv(fd,vec,iovcnt);//返回读取到的字节数
    if(n<0)
    {
        *saveError=errno;
    }
    else if(n<=writable)//数据全部写入 Buffer；
    {
        writerIndex_+=n;
    }
    else//extrabuf中也写入了数据
    {
        writerIndex_=buffer_.size();
        append(extrabuf,n-writable);
    }
    return n;
 }

 ssize_t Buffer::writeFd(int fd,int* saveErrno)
 {
    ssize_t n=::write(fd,peek(),readableBytes());
    if(n>0)
    {
        retrieve(n);  // 消费已发送的数据
    }
    else
    {
        *saveErrno=errno;
    }
    return n;
 }